import React, { useState, useEffect } from 'react';
import { Modal, Form, Button, Input, Select, InputNumber, Upload } from 'antd';
import { ProFormUploadButton } from '@ant-design/pro-form';
import { upload } from '@/services/ant-design-pro/apis';
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
import { message } from 'antd';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

const UpdateBrand = (props) => {
  const formLayout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 15,
    },
  };

  const { onSubmit: handleUpdate, onCancel: handleModalVisible, updateModalVisible } = props;

  const [formVals, setFormVals] = useState({
    id: props.values.id,
    brandName: props.values.brandName,
    brandId: props.values.brandId,
    brandImg: props.values.brandImg,
    status: props.values.status,
  });

  const handleSubmit = async () => {
    try {
      const fieldVlas = await form.validateFields();
      fieldVlas.brandImg = fileName;
      console.log(fieldVlas);
      handleUpdate({ ...fieldVlas });

      setFileList([]);
      setUploaded(false);

      onReset();
    } catch (err) {
      console.log(err);
    }
  };

  const onReset = () => {
    form.resetFields();
  };

  const [uploaded, setUploaded] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [fileName, setFileName] = useState('');

  useEffect(() => {
    // 根据 formVals.productPicture 设置 fileList 的初始值
    if (formVals.brandImg.trim() !== '') {
      setFileName(formVals.brandImg);
      setFileList([
        {
          uid: '1',
          name: formVals.brandImg,
          status: 'done',
          url: formVals.brandImg,
        },
      ]);
    } else {
      setFileList([]);
    }
  }, [formVals.brandImg]);

  // 处理返回结果
  function normFile(e) {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }

  // 文件上传
  const handleCustomRequest = ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('uploadfile', file);

    // 执行自定义上传请求
    fetch('/api/brand/image', {
      method: 'POST',
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        // 处理响应
        console.log(data);
        onSuccess(data, file);
        setFileName(data.data.split('\\')[5]);
      })
      .catch((error) => {
        // 处理错误
        onError(error, file);
      });
  };

  // 上传之前处理图片
  function beforeUpload(file) {
    const isImage = file.type.startsWith('image/');

    if (!isImage) {
      message.error('只能上传图片文件！', 2);
      return false;
    }
    if (uploaded) {
      message.error('只能上传一张图片', 2);
      return false;
    }

    setUploaded(true);

    const newFileList = [...fileList, file];
    setFileList(newFileList);
    return isImage;
  }

  // 删除图片
  function onRemove(file) {
    console.log(`Removed file: ${file.name}`);

    // 发送删除文件请求到后端
    axios
      .delete(`/api/brand/delBrandPicture/` + fileName)
      .then((response) => {
        console.log(response.data.success);
        if (!response.data.success) {
          message.error(response.data.message, 2);
        }
        setUploaded(false);
        setFileList([]);
      })
      .catch((error) => {});
  }

  const [form] = Form.useForm();

  return (
    <Modal
      title="配置分类"
      width={540}
      visible={updateModalVisible}
      destroyOnClose
      onCancel={() => {
        onReset();
        handleModalVisible(false);
      }}
      footer={[
        <Button
          key="reset"
          onClick={() => {
            handleModalVisible();
          }}
        >
          取消
        </Button>,
        <Button
          type="primary"
          key="submit"
          onClick={() => {
            handleSubmit();
          }}
        >
          提交
        </Button>,
      ]}
    >
      <Form
        {...formLayout}
        initialValues={{
          status: formVals.status,
          id: formVals.id,
          brandName: formVals.brandName,
          brandId: formVals.brandId,
          brandImg: formVals.brandImg,
          file: formVals.brandImg
            ? [
                {
                  uid: '1',
                  name: formVals.brandImg,
                  status: 'done',
                  url: `/product-picture/` + formVals.brandImg,
                },
              ]
            : undefined, // 如果brandImg不存在，将file设置为undefined
        }}
        form={form}
      >
        <FormItem label="状态" name="status">
          <Select>
            <Option value="ENABLE">启用</Option>
            <Option value="FORBIDDEN">禁用</Option>
          </Select>
        </FormItem>

        <Form.Item
          label="产品图片"
          name="file"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          rules={[
            {
              required: true,
              message: '请上传产品图片',
            },
          ]}
        >
          <Upload
            name="uploadfile"
            listType="picture-card"
            customRequest={handleCustomRequest}
            action="/api/brand/image" // 上传图片的服务端接口
            beforeUpload={beforeUpload}
            onRemove={onRemove}
          >
            {fileList.length > 0 ? null : <Button icon={<UploadOutlined />}>点击上传</Button>}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UpdateBrand;
